<?php
declare (strict_types = 1);

namespace app\common\service;

use think\File;
use think\Exception;

/**
 * 上传服务类
 * Class UploadService
 * @package app\common\service
 */
class UploadService
{
    /**
     * 上传素材
     * @param File $file 上传的文件
     * @param string $type 素材类型
     * @return array
     */
    public static function uploadMaterial($file, $type = 'image')
    {
        if (!$file) {
            return ['code' => 1, 'msg' => '未找到上传文件'];
        }
        
        // 检查文件类型
        $allowedTypes = [
            'image' => ['jpg', 'jpeg', 'png', 'gif'],
            'video' => ['mp4', 'avi', 'mov'],
            'audio' => ['mp3', 'wav', 'ogg'],
            'document' => ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']
        ];
        
        $extension = strtolower($file->getExtension());
        if (isset($allowedTypes[$type]) && !in_array($extension, $allowedTypes[$type])) {
            return ['code' => 1, 'msg' => '文件类型不允许'];
        }
        
        // 上传目录
        $uploadDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . $type . DS . date('Ymd');
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        // 生成文件名
        $fileName = md5(uniqid(mt_rand(), true)) . '.' . $extension;
        $savePath = $uploadDir . DS . $fileName;
        
        try {
            // 保存文件
            $file->move($uploadDir, $fileName);
            
            // 返回结果
            $fileUrl = '/uploads/' . $type . '/' . date('Ymd') . '/' . $fileName;
            return [
                'code' => 0,
                'msg' => '上传成功',
                'data' => [
                    'path' => str_replace(ROOT_PATH . 'public', '', $savePath),
                    'url' => $fileUrl,
                    'original_name' => $file->getInfo('name'),
                    'size' => $file->getSize(),
                    'extension' => $extension
                ]
            ];
        } catch (Exception $e) {
            return ['code' => 1, 'msg' => '上传失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 删除素材
     * @param string $path 文件路径
     * @return array
     */
    public static function deleteMaterial($path)
    {
        if (empty($path)) {
            return ['code' => 1, 'msg' => '文件路径不能为空'];
        }
        
        $filePath = ROOT_PATH . 'public' . $path;
        
        if (!file_exists($filePath)) {
            return ['code' => 2, 'msg' => '文件不存在'];
        }
        
        try {
            if (unlink($filePath)) {
                return ['code' => 0, 'msg' => '删除成功'];
            } else {
                return ['code' => 1, 'msg' => '删除失败'];
            }
        } catch (Exception $e) {
            return ['code' => 1, 'msg' => '删除失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 上传头像
     * @param File $file 上传的文件
     * @param int $userId 用户ID
     * @return array
     */
    public static function uploadAvatar($file, $userId)
    {
        if (!$file) {
            return ['code' => 1, 'msg' => '未找到上传文件'];
        }
        
        // 检查文件类型
        $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
        $extension = strtolower($file->getExtension());
        if (!in_array($extension, $allowedTypes)) {
            return ['code' => 1, 'msg' => '头像只支持JPG、JPEG、PNG、GIF格式'];
        }
        
        // 上传目录
        $uploadDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'avatar';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        // 生成文件名
        $fileName = 'avatar_' . $userId . '_' . time() . '.' . $extension;
        
        try {
            // 保存文件
            $file->move($uploadDir, $fileName);
            
            // 返回结果
            $fileUrl = '/uploads/avatar/' . $fileName;
            return [
                'code' => 0,
                'msg' => '上传成功',
                'data' => [
                    'path' => '/uploads/avatar/' . $fileName,
                    'url' => $fileUrl
                ]
            ];
        } catch (Exception $e) {
            return ['code' => 1, 'msg' => '上传失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 删除文件
     * @param string $path 文件路径
     * @return bool
     */
    public static function deleteFile($path)
    {
        if (empty($path)) {
            return false;
        }
        
        $filePath = ROOT_PATH . 'public' . DS . $path;
        
        if (file_exists($filePath)) {
            return unlink($filePath);
        }
        
        return false;
    }
} 